package javagprssrv.Common;

public class CRC
{
    public static java.lang.String CRC16(final java.lang.String str) {
        java.lang.String res = "";
        final java.lang.String s = str;
        final int[] buf = new int[1000];
        int SaveHi = 0;
        int SaveLo = 0;
        for (int i = 0; i < s.length(); ++i) {
            buf[i] = s.charAt(i);
        }
        int CRC16Lo = 0;
        int CRC16Hi = 0;
        final int CL = 1;
        final int CH = 160;
        for (int i = 0; i < s.length(); ++i) {
            CRC16Lo ^= buf[i];
            for (int flag = 0; flag < 8; ++flag) {
                SaveHi = CRC16Hi;
                SaveLo = CRC16Lo;
                if (CRC16Hi % 2 == 1) {
                    CRC16Hi = (CRC16Hi - 1) / 2;
                }
                else {
                    CRC16Hi /= 2;
                }
                if (CRC16Lo % 2 == 1) {
                    CRC16Lo = (CRC16Lo - 1) / 2;
                }
                else {
                    CRC16Lo /= 2;
                }
                if (SaveHi % 2 == 1) {
                    CRC16Lo |= 0x80;
                }
                CRC16Hi &= 0xFF;
                if (SaveLo % 2 == 1) {
                    CRC16Hi ^= CH;
                    CRC16Lo ^= CL;
                }
                CRC16Hi &= 0xFF;
                CRC16Lo &= 0xFF;
            }
        }
        CRC16Hi &= 0xFF;
        CRC16Lo &= 0xFF;
        res = java.lang.String.valueOf((char)CRC16Lo) + java.lang.String.valueOf((char)CRC16Hi);
        return res;
    }
}
